package net.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 群聊系统服务端
 *
 * @author 王霄
 * @date 2021/9/7 11:40
 **/
public class GroupCharServer {

    private int port;

    public GroupCharServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup parentGroup = new NioEventLoopGroup(1);
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<ServerChannel>() {
                        @Override
                        protected void initChannel(ServerChannel ch) throws Exception {
                            ch.pipeline().addLast("decoder", new StringDecoder())//想管道里面加入解码器
                                    .addLast("encoder", new StringEncoder())//想管道里面加入编码码器
                                    .addLast(null);
                        }
                    });
            System.out.println("netty服务器启动成功");
            ChannelFuture future = bootstrap.bind(port).sync();
            //对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        new GroupCharServer(7777).run();
    }
}
